import { API_URL, ISProduct, FILE_VIEW } from "src/config";
import { Base64 } from "js-base64";
import assignWith from "lodash/assignWith";
import { cloneDeep } from "lodash";

/***
 * 遍历树
 */
export function mapTree(tree, iterator, level = 1, depthFirst = false, paths = [], path) {
    return tree.map((item, index) => {
        if (depthFirst) {
            let children = item.children
                ? mapTree(
                      item.children,
                      iterator,
                      level + 1,
                      depthFirst,
                      paths.concat(path ? item[path] : index),
                      path,
                  )
                : undefined;
            children && (item = { ...item, children: children });
            item = iterator(item, index, level, paths) || { ...item };
            return item;
        }

        item = iterator(item, index, level, paths) || { ...item };

        if (item.children && item.children.splice) {
            item.children = mapTree(
                item.children,
                iterator,
                level + 1,
                depthFirst,
                paths.concat(path ? item[path] : index),
                path,
            );
        }

        return item;
    });
}

/**
 * 在树中查找节点。
 * @param tree
 * @param iterator
 */
export function findTree(tree, iterator) {
    let result = null;

    everyTree(tree, (item, key, level, paths) => {
        if (iterator(item, key, level, paths)) {
            result = item;
            return false;
        }
        return true;
    });

    return result;
}

/**
 * 判断树中每个节点是否满足某个条件。
 * @param tree
 * @param iterator
 */
export function everyTree(tree, iterator, level, paths, indexes = []) {
    return tree.every((item, index) => {
        const value = iterator(item, index, level, paths, indexes);

        if (value && item.children && item.children.splice) {
            return everyTree(
                item.children,
                iterator,
                level + 1,
                paths.concat(item),
                indexes.concat(index),
            );
        }

        return value;
    });
}

/**
 *
 * @param {function} func 原函数
 * @return {Boolean} 是否为函数
 */
export function isFunction(func) {
    if (!func) {
        return false;
    }
    return (
        typeof func === "function" || Object.prototype.toString.call(func) === "[object Function]"
    );
}

/**
 * 获取地址栏query参数
 * @param search
 */
export const getSearchParams = (search = "") => {
    let obj = {};
    search.indexOf("?") > -1 && (search = search.split("?")[1]);
    let arr = search.split("&");
    for (let o in arr) {
        let key = arr[o].split("=");
        obj[key[0]] = key[1];
    }
    return obj;
};

export function mergeProps(...items) {
    function customizer(objValue, srcValue) {
        return srcValue === undefined ? objValue : srcValue;
    }

    let ret = { ...items[0] };
    for (let i = 1; i < items.length; i++) {
        ret = assignWith(ret, items[i], customizer);
    }
    return ret;
}

/**
 *合并两个对象
 * @param a {Object}
 * @param b {Object}
 */
export const merge = function (a, b) {
    for (let key in b) {
        a[key] = b[key];
    }
};

/**
 * 生成随机GUID
 * @return {string}
 */
export function guid() {
    return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
        .replace(/[xy]/g, function (c) {
            const r = (Math.random() * 16) | 0,
                v = c === "x" ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        })
        .toUpperCase();
}

export const isFormData = data => {
    return Object.prototype.toString.call(data) === "[object FormData]";
};

export function refreshPage(page) {
    sessionStorage.setItem("refreshPages", JSON.stringify(page || true));
}

export function clearRefreshPage(cb) {
    if (sessionStorage.getItem("refreshPages")) {
        sessionStorage.removeItem("refreshPages");
        cb && cb();
    }
}

//页面跳转
export function toPage(pageData, store, history) {
    const { key, toPageData, from } = pageData;
    let pageParams = sessionStorage.getItem("pageParams") || "{}";
    pageParams = JSON.parse(pageParams);
    pageParams[key] = {
        toPageData,
        from,
    };
    sessionStorage.setItem(JSON.stringify(pageParams));
}

export function getPageParams(search) {
    let params = {};
    if (search) {
        params = getSearchParams(search);
    }
    let pageParams = sessionStorage.getItem("pageParams");
    if (params.key) {
        pageParams = pageParams && JSON.parse(pageParams);
        params = cloneDeep(pageParams[params.key]);
        delete pageParams[params.key];
        sessionStorage.setItem(JSON.stringify(pageParams));
        return params;
    }
    return params;
}

export function PreviewPdf(url) {
    if (ISProduct) {
        url = url.replace("https://apps.r93535.com/sxgcbsbepdf", "http://127.0.0.1:7048");
    }
    try {
        if (isWeixinMiniProgram()) {
            console.log("当前环境是微信小程序");
            window.wx?.miniProgram?.navigateTo({
                url:
                    "/pages/modules/quality-form/pdfview/pdfview?pdfUrl=" + encodeURIComponent(url),
            });
        } else if (isUniApp()) {
            console.log("当前环境是UniApp");
            window.uni?.navigateTo({
                url:
                    "/pages/modules/quality-form/pdfview/pdfview?pdfUrl=" + encodeURIComponent(url),
            });
        } else {
            // const onlineUrl = `${FILE_VIEW}/onlinePreview?url=${encodeURIComponent(
            //     Base64.encode(url),
            // )}`;
            const onlineUrl = `${FILE_VIEW}/onlinePreview?encryptPath=${url}&isApp=1`;
            window.open(onlineUrl);

            //原生app预览方法
            // window.openPdf(url);
        }
    } catch (error) {
        console.log(error);
        // window?.openPdf(url);
    }
}

function isWeixinMiniProgram() {
    const wx = window.wx;
    return typeof wx !== "undefined" && wx !== null && typeof wx.getSystemInfoSync === "function";
}

function isUniApp() {
    const uni = window.uni;
    return (
        typeof uni !== "undefined" && uni !== null && typeof uni.getSystemInfoSync === "function"
    );
}

export function isNormalBrowser() {
    return !(isWeixinMiniProgram() || isUniApp());
}
